<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品ID" prop="gid">
        <el-input
          v-model="queryParams.gid"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类ID" prop="cid">
        <el-input
          v-model="queryParams.cid"
          placeholder="请输入分类ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="gname">
        <el-input
          v-model="queryParams.gname"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="gsn">
        <el-input
          v-model="queryParams.gsn"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="gid" />
      <el-table-column label="分类ID" align="center" prop="cid" />
      <el-table-column label="商品名称" align="center" prop="gname" />
      <el-table-column label="商品图片" align="center" prop="gimg" >
        <template slot-scope="scope" v-if="scope.row.gimg">
          <img v-if="scope.row.gimg" :src="$baseUrl + '/' + scope.row.gimg" width="50px" height="50px" />
        </template>
      </el-table-column>
      <el-table-column label="商品编号" align="center" prop="gsn" />
      <el-table-column label="原价" align="center" prop="price" />
      <el-table-column label="促销价" align="center" prop="saleprice" />
      <el-table-column label="商品描述" align="center" prop="description" />
      <el-table-column label="商品标题" align="center" prop="detailtitle" />
      <el-table-column label="库存数量" align="center" prop="stock" />
      <el-table-column label="低库存阈值" align="center" prop="lowstock" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="商品重量" align="center" prop="weight" />
      <el-table-column label="发布状态" align="center" prop="publishstate" />
      <el-table-column label="赠送积分" align="center" prop="giftpoint" />
      <el-table-column label="审核状态" align="center" prop="verifystate" />
      <el-table-column label="送达时间" align="center" prop="sendtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="salesnum" />
      <el-table-column label="销售总额" align="center" prop="sumsales" />
      <el-table-column label="备注" align="center" prop="note" />
      <el-table-column label="排序序号" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改goodss对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类ID" prop="cid">
          <el-input v-model="form.cid" placeholder="请输入分类ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="gname">
          <el-input v-model="form.gname" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="gimg">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/upload'"
            :headers="{ Authorization: 'Bearer ' + $store.getters.token }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.gimg"
              :src="$baseUrl + '/' + form.gimg"
              class="avatar"
              style="width: 100px; height: 100px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品编号" prop="gsn">
          <el-input v-model="form.gsn" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="原价" prop="price">
          <el-input v-model="form.price" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="促销价" prop="saleprice">
          <el-input v-model="form.saleprice" placeholder="请输入促销价" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品标题" prop="detailtitle">
          <el-input v-model="form.detailtitle" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="低库存阈值" prop="lowstock">
          <el-input v-model="form.lowstock" placeholder="请输入低库存阈值" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="商品重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入商品重量" />
        </el-form-item>
        <el-form-item label="发布状态" prop="publishstate">
          <el-input v-model="form.publishstate" placeholder="请输入发布状态" />
        </el-form-item>
        <el-form-item label="赠送积分" prop="giftpoint">
          <el-input v-model="form.giftpoint" placeholder="请输入赠送积分" />
        </el-form-item>
        <el-form-item label="审核状态" prop="verifystate">
          <el-input v-model="form.verifystate" placeholder="请输入审核状态" />
        </el-form-item>
        <el-form-item label="送达时间" prop="sendtime">
          <el-date-picker clearable
            v-model="form.sendtime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择送达时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售数量" prop="salesnum">
          <el-input v-model="form.salesnum" placeholder="请输入销售数量" />
        </el-form-item>
        <el-form-item label="销售总额" prop="sumsales">
          <el-input v-model="form.sumsales" placeholder="请输入销售总额" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序序号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/system/goods";

export default {
  name: "Goods",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // goodss表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gid: null,
        cid: null,
        gname: null,
        gimg: null,
        gsn: null,
        price: null,
        saleprice: null,
        description: null,
        detailtitle: null,
        stock: null,
        lowstock: null,
        unit: null,
        weight: null,
        publishstate: null,
        giftpoint: null,
        verifystate: null,
        sendtime: null,
        salesnum: null,
        sumsales: null,
        note: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cname: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询goodss列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.data.rows;
        this.total = response.data.totalsize;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        gid: null,
        cid: null,
        gname: null,
        gimg: null,
        gsn: null,
        price: null,
        saleprice: null,
        description: null,
        detailtitle: null,
        stock: null,
        lowstock: null,
        unit: null,
        weight: null,
        publishstate: null,
        giftpoint: null,
        verifystate: null,
        sendtime: null,
        salesnum: null,
        sumsales: null,
        note: null,
        sort: null
      };
      this.$nextTick(() => {
        this.$refs['form'].resetFields();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.gid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加goodss";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const gid = row.gid || this.ids
      getGoods(gid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改goodss";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.gid != null) {
            updateGoods(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const gids = row.gid || this.ids;
      this.$modal.confirm('是否确认删除goodss编号为"' + gids + '"的数据项？').then(function() {
        return delGoods(gids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB！');
        return false;
      }
      return isImage && isLt2M;
    },
    /** 上传成功处理 */
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.form.gimg = res.data; // 确保使用正确的字段名
        this.$message.success("上传成功");
      } else {
        this.$message.error(res.msg || "上传失败");
      }
    }
  }
};
</script>
